package com.woniuxy.movie.gateway.filter;

import com.woniuxy.movie.commons.core.util.JwtUtil;
import com.woniuxy.movie.gateway.config.AuthenUrlProperties;
import com.woniuxy.movie.gateway.exception.AuthenException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@Order(1)
public class AdminLoginAuthenFilter implements GlobalFilter {

    @Autowired
    private AuthenUrlProperties aup;

    private static AntPathMatcher apm = new AntPathMatcher();

    /**
     * 匹配公共放行的url
     * @param aup
     * @param url
     * @return
     */
    public static boolean match(AuthenUrlProperties aup,String url){
        if (aup.getBaseUrls()!=null) {
            for (String pat : aup.getBaseUrls()) {
                if (apm.match(pat,url)) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String url = exchange.getRequest().getPath().toString();
        //判断是否需要放行
        if (AdminLoginAuthenFilter.match(aup,url)) {
            return chain.filter(exchange);
        }
        if(aup.matchAdmin(url)){
            return chain.filter(exchange);
        }
        //判断是否是后端请求
        int index = url.lastIndexOf(".");
        if (index==-1) {
            return chain.filter(exchange);
        }else if(!(url.substring(index).equals(".api"))){
            return chain.filter(exchange);
        }

        //认证
        System.out.println("---------开始认证管理员端登录状态--------------");
        List<String> tokens = exchange.getRequest().getHeaders().get("authen_token");
        if (tokens==null||tokens.size()<=0) {
            throw new AuthenException(401,"未登录");
        }
        String token = tokens.get(0);
        try {
            JwtUtil.parseAdminToken(token);
        } catch (Exception e) {
            e.printStackTrace();
            throw new AuthenException(401,"未登录");
        }
        return chain.filter(exchange);
    }

    public static void main(String[] args) {
        System.out.println(JwtUtil.createUserToken("userId",1));
    }
}
